package com.cnsuning.jobtool.jobtools.mycat.hashfactor;

import com.alibaba.fastjson.JSON;
import com.cnsuning.jobtool.utils.ExcelUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class ConfigJsonGenerator {
    @Test
    public void start() throws IOException, InvalidFormatException {
        String targetFileName = "src/main/java/com/cnsuning/jobtool/jobtools/mycat/hashfactor/result.json";
        //读取excel
        String fileName = "src/main/java/com/cnsuning/jobtool/jobtools/mycat/hashfactor/config.xlsx";
        File file = new File(fileName);
        List<String> columns = new ArrayList<>();
        columns.add("orderId");
        columns.add("factor");
        columns.add("offset");
        Map<String,List<String>> columnsMap = new HashMap<>();
        columnsMap.put("config",columns);
        Map<String, List<LinkedHashMap<String, Object>>> resultMap = ExcelUtils.readExcelHasTitle(file, columnsMap);
        List<LinkedHashMap<String, Object>> rowsList = resultMap.get("config");
        String resultJson = "[]";
        if (!CollectionUtils.isEmpty(rowsList))
        {
;
            for (LinkedHashMap<String, Object> row :rowsList){
                row.put("orderId",row.get("orderId")+"");
                row.    put("factor",(int)Float.parseFloat(row.get("factor")+""));
                row.put("offset",(int)Float.parseFloat(row.get("offset")+""));
            }
            resultJson = JSON.toJSONString(rowsList);
        }
        FileUtils.writeStringToFile(new File(targetFileName),resultJson,"utf-8",false);
    }
}
